package com.adu.music;

import com.adu.music.proxy.ProxySpider;
import com.adu.music.spider.*;
import com.adu.music.util.ConfigManager;
import com.adu.music.util.JsoupUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.time.LocalTime;
import java.time.ZoneId;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

/**
 * 一个简单的网易云音乐爬虫
 * 爬虫入口
 */
public class App {
    private static final Logger logger = LoggerFactory.getLogger(App.class);
    // spider开始时间是早晚8点
    private static final LocalTime spiderTime = ConfigManager.getSpiderTime();
    public static void main(String[] args) {
        if(ConfigManager.getUseProxy()){
            startScheduleProxySpiderTask();
        }
        startScheduleMusicSpiderTask();
    }

    private static void startTask(AbstractSpider spider) {
        spider.startTask();
    }

    private static void doSpiderTask() {
        logger.info("json utils opening proxy pool");
        // 打开代理池
        JsoupUtils.openProxyPool();
        logger.info("--------- start MV update spider -----------------------");
        startTask(new MvUpdateSpider());
        logger.info("--------- start playlist update spider -----------------");
        startTask(new PlaylistUpdateSpider());
        logger.info("--------- start song update spider ---------------------");
        startTask(new SongUpdateSpider());
        logger.info("all spider task completed , yeah~~~");
        JsoupUtils.releaseResources();
        logger.info("json util released resources~~~");
    }

    /**
     * 开启抓取定时任务
     */
    private static void startScheduleMusicSpiderTask() {
        ScheduledExecutorService exec = Executors.newSingleThreadScheduledExecutor();
        LocalTime now = LocalTime.now(ZoneId.of("Asia/Shanghai"));
        int initialDelay = spiderTime.toSecondOfDay() - now.toSecondOfDay();
        final int delay = 12 * 3600;
        if (initialDelay < 0) initialDelay = 12 * 60 * 60 + initialDelay;
        else if (initialDelay > delay) initialDelay = delay * 2 - initialDelay;
        logger.info("it is left {} minutes for start music spider", initialDelay / 60);
        exec.scheduleWithFixedDelay(App::doSpiderTask, initialDelay, delay, TimeUnit.SECONDS);
    }

    /**
     * 开启更新代理定时任务
     */
    private static void startScheduleProxySpiderTask() {
        ScheduledExecutorService exec = Executors.newSingleThreadScheduledExecutor();
        final int delay = 4 * 3600; // 间隔4个小时
        logger.info("proxy spider starting ......");
        exec.scheduleWithFixedDelay(new ProxySpider(), 0, delay, TimeUnit.SECONDS);
    }
}
